﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.Thread
{
    public class MesDataPush
    {
        OrderDao orderDao = new OrderDao();
        ViewDao viewDao = new ViewDao();

        public async Task pushTask()
        {
            Tools.ProduceLogText("Mes数据推送线程启动成功！");

            while (true)
            {
                await Task.Delay(100);

                try
                {
                    List<OrderStatus> orderStatuses = orderDao.GetOrder();

                    List<OrderTrace> orderTraces = orderDao.QueryOrderTrace();

                    if (orderTraces?.Count > 0)
                    {
                        foreach (OrderTrace orderTrace in orderTraces)
                        {
                            OrderStatus orderStatus = orderStatuses.Where(x => x.OrderId == orderTrace.OrderId).FirstOrDefault();

                            if (orderTrace == null || orderStatus == null)
                                continue;

                            string dataFrom = orderTrace.LineName;

                            string dataId = Tools.GetHashCodeFromPushMes(orderTrace.OrderId, orderTrace.TraceId, orderTrace.CreateTime);

                            if (orderTrace.Status1.Equals("0"))
                                PushPart(orderTrace, dataId, dataFrom, orderTrace.Id);

                            if (orderTrace.Status2.Equals("0"))
                                StationPart(orderTrace, dataId, dataFrom, orderStatus.MaterialId);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Tools.ProduceLogTextError($"组装或者推送工厂Mes数据失败，原因是{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 推送明暗码
        /// </summary>
        /// <returns></returns>
        public async Task CodePushTask()
        {
            Tools.ProduceLogText("明暗码推送线程启动成功！");

            while (true)
            {
                await Task.Delay(1000);

                try
                {
                    List<TracePoint> tracePoints = new List<TracePoint>();
                    //拿到未推送的明暗码
                    for (int i = 0; i < 10; i++)
                    {

                        List<TracePoint> pointStatus = orderDao.QueryPoint("1", i);

                        tracePoints.AddRange(pointStatus);

                    }

                    if (tracePoints?.Count > 0)
                    {

                        foreach (var item in tracePoints)
                        {
                            string dataDtlId = Tools.GetHashCodeFromPushMes(item.TraceId, item.PointCode, item.CreateTime);

                            bool isOk = orderDao.UpdatePointSaveStatus(item.Id, item.TraceId);

                            int count = viewDao.PushPointData(new LineMesDataBarcodeRelation()
                            {
                                Id = dataDtlId,
                                TraceNo = item.TraceId,
                                ViewCode = item.PointCode,
                                CreateTime = item.CreateTime,
                                DataFrom = "德恒W04前纵线",
                                EqptId = item.Station,
                                DataType = "normal"
                            });

                        }

                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"推送明暗码失败，原因是{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 推送单件数据
        /// </summary>
        /// <param name="orderTrace"></param>
        /// <param name="code"></param>
        /// <param name="dataFrom"></param>
        private void PushPart(OrderTrace orderTrace, string dataId, string dataFrom, int id)
        {
            try
            {
                // 推送单件上件绑定数据
                int count = viewDao.PushPartData(new LineMesData()
                {
                    OrderId = orderTrace.OrderId,
                    TraceId = orderTrace.TraceId,
                    CreateTime = orderTrace.CreateTime,
                    DataFrom = dataFrom,
                    DataId = dataId,
                });

                if (count > 0)
                {
                    orderDao.UpdatePushOkStatus(id);
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"推送单件数据失败，原因是{e.Message}");
            }
        }

        /// <summary>
        /// 推送过站数据
        /// </summary>
        /// <param name="orderTrace"></param>
        /// <param name="code"></param>
        /// <param name="dataFrom"></param>
        private void StationPart(OrderTrace orderTrace, string dataId, string dataFrom, string materialId)
        {
            try
            {
                // 获取过站信息
                List<PartProcess> partProcesses = orderDao.GetProcessDataByTraceId(orderTrace.TraceId);

                foreach (var partProcess in partProcesses)
                {
                    string material = MappingTable.GetMaterialByStation(partProcess.Station);

                    if (string.IsNullOrEmpty(materialId) || !materialId.Equals(material))
                        continue;

                    if (partProcess.IsSave != null && partProcess.IsSave.Equals("1"))
                        continue;

                    if (string.IsNullOrEmpty(partProcess.Operation))
                        continue;

                    string[] operations = partProcess.Operation.Split(',');

                    foreach (string operation in operations)
                    {
                        string stationCode = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, operation, partProcess.StartTime);

                        // 拼接过站数据进行推送
                        int stationDataRecord = viewDao.PushStationData(new LineMesDataTrace()
                        {
                            DataId = dataId,
                            DataTraceId = stationCode,
                            Station = partProcess.Station,
                            Process = operation,
                            Result = partProcess.Result,
                            CreateTime = partProcess.StartTime == DateTime.MinValue ? partProcess.EndTime : partProcess.StartTime,
                            StartTime = partProcess.StartTime,
                            EndTime = partProcess.EndTime,
                            DataFrom = dataFrom,
                            UserId = "",
                        },"1");

                        if (stationDataRecord > 0)
                        {
                            orderDao.UpDateStationStatus(partProcess.Id, orderTrace.TraceId);
                        }
                    }

                    if (MappingTable.GetEndStation(partProcess.Station))
                    {
                        // 更新数据
                        orderDao.UpdateStatus2(orderTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"推送过站数据失败，原因是{ex.Message}");
            }
        }
    }
}
